#include "Led_matrix.h"

#define NUMDEV 7
#define X_MAX 23
#define Y_MAX 15

matrix m;
int CS[] = {4,5,6,7,8,9,10};
void setup()
{
  int dev;
  Serial.begin(19200);
 //  Serial.begin(57600);
//  Serial.begin(115200);
  m.setData(11);
  m.setWrite(12);
  for (dev=0;dev<NUMDEV;dev++){
    m.setCS(CS[dev]);
    m.setup();
  }
}

void demo_serial_plot ()
{
  int i, index, dev;
  byte val;
  byte mybuffer[48*NUMDEV];
  static byte lamps[32];
  
  if (Serial.available()) {
    val = Serial.read();
    if (val == 'D'){
      for (dev=0;dev<NUMDEV;dev++){
     //   Serial.print('J', BYTE);
        for (i=0;i<48;i++){
          while(Serial.available() == 0) {}
          mybuffer[48*dev + i] = Serial.read();
        }
      }
   //   Serial.print('D', BYTE);

//este "for" só serve pra visualizar os dados da paleta no DMD
      for (i=0;i<32;i+=2){
//        mybuffer[48*3 + i] = lamps[i+1];
//        mybuffer[48*3 + i+1] = lamps[i];
      }

        index=0;        
        for (dev=0;dev<NUMDEV;dev++){
          m.setCS(CS[dev]);
          
          for (i=0;i<48;i++){
              val = mybuffer[index++];
              m.ht1632_shadowram[2*i] = (val & 0xf0) >> 4;
              m.ht1632_shadowram[2*i+1] = val & 0x0f;
          }
          m.ShadowDsp();
        }
        return;
    }

    if (val=='L'){
      for(i=0;i<32;i++){ //mudar para 8! receber lâmpadas. estamos recebendo paleta
          while(!Serial.available()) {}
          lamps[i] = Serial.read();        
      }
      return;
    }

  }
}

void loop()
{
  demo_serial_plot();
}

